package com.kdtech.analyse.news;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 * 金湾区人民政府
 */
public class JinwangovNewsAnalyse implements AnalyseNews{
	
	private static final String[] regex={
		"http://www.jinwan.gov.cn/ShowDetail.aspx[?]ID=[a-z0-9]*",
		"http://www.jinwan.gov.cn/ConsultingDetail.aspx[?]ID=[a-z0-9]*",
	};	
	
	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}		
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();	
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);				
		news.setUrl(url);	
		if(url.indexOf("ShowDetail")>0){
			title =doc.select("td.fonth19").text();	
			content=HtmlCleaner.getContentHtml(url,doc.select("td.fonth21"));
			date=DateUtils.matchDate(doc.select("td.fonth22").text());
			
		}else{
			Elements elements = doc.select("td.hdtable_txt");
			if(elements!=null&&elements.size()>0){
				title = elements.get(0).text();
				author = elements.get(1).text();
				content = elements.get(4).text();
				date = DateUtils.matchDate(elements.get(6).text());
			}
		}
		
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);	
		news.setType(1);	
		return news;
	}	
	public static void main(String[] args) {
		String url="http://www.jinwan.gov.cn/ConsultingDetail.aspx?ID=c02962b656394047b356c68ab93023b1";
		JinwangovNewsAnalyse analyse=new JinwangovNewsAnalyse();		
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
